<?php

define("ALL_PROJECTS_DIR", "../../projects_files/");

include_once '../../lib/config.php';
include_once '../../lib/classes/Class_Member.php';

$connection = new Member();
$connection->login();

if(!$connection->isConnected())
    exit;
if(!isset($_SESSION['member_session']['team']))
    exit;

$target = $_POST['target']; // dossier à explorer
$action = $_POST['action'];

//si l'utilisateur appartient bien au projet
	switch($action){
		case "browse":
			file_list($target);
			break;
		case "remove":
			remove_file($target);
		case "remove_dir":
			
			//remove_file($target);
			
			if(dirname($target) == "." || dirname($target) == ""){
				file_list("");
			}else{
				file_list(dirname($target).'/');
			}
			
			break;
		case "create_dir":
			$dir_name = $_POST['dirname'];
			create_dir($target, $dir_name);
			break;
		case "preview":
			preview($target);
			break;
		case "edit":
			edit_file($target);
			break;
		case "send_edit":
			send_edit($target, $_POST['content']);	
	}
//fin de si


//Liste des fichiers
function file_list($target){
	
	$dir = ALL_PROJECTS_DIR.$_SESSION['member_session']['team'].'/'.$target;

	for ($i = 0; $i < 2; $i++){
		
		if ($handle = opendir($dir)) {

		    while (false !== ($file = readdir($handle))) {
		        if ($file != "." && $file != "..") {

		        	if(!(substr($file, 0, 1) == ".")){ // on n'affiche pas les fichiers cachés

                                    //echo $dir.$file;
			            if(is_dir($dir.$file) && $i == 0){

			            	echo "<tr class=\"directory\" id=\"$file/\"><td><div class=\"file_info\">$file</div><div class=\"file_options\">".isDownloadable($target.$file)." ".isRemovable($target.$file)."</div></td></tr>";
			            }else if(is_file($dir.$file) && $i == 1){

			            	if($file != ".DS_Store"){

			            		echo "<tr class='file' id =\"$file\"><td><div class=\"file_info\">$file</div><div class=\"file_options\">".isDownloadable($target.$file)." ".hasPreview($target.$file)." ".isEditable($target.$file)." ".isRemovable($target.$file)."</div></td></tr>";
			            		
			            	}
			            }
			        
			        }
		        }
		    }
		    
		    closedir($handle);
			    	    
		}
	
	}
}



function remove_file($target){
		
	$path = ALL_PROJECTS_DIR.$_SESSION['member_session']['team'].'/'.$target;
	
	if(is_dir($path)){
	
		remove_dir($path);
		
	}else{
	
		unlink($path);
	}
	
	//actualisation de la page
	//$parent_dir1 = preg_replace("#^(.+/)*.+/?$#", "$1", $target);
	$parent_dir = dirname($target);
	if(substr($parent_dir, -1) != "/"){
		$parent_dir .= '/';
	}
	
	//file_list($parent_dir);
}

function remove_dir($path){

	if ($handle = opendir($path)) {
				
	    while (false !== ($file = readdir($handle))) {
						
			if ($file != "." && $file != "..") {
							
				if (is_file($path.$file)){
					
					unlink($path.$file); // suppression du fichier
						
				}elseif (is_dir($path.$file)){
				
					remove_dir($path.$file.'/');
					
					//rmdir($path.$file); // suppression du dossier
					
				}
							
			}
			
	    }

	closedir($handle);
			
	}
		
	rmdir($path);


}

function create_dir($target, $name){
	
	$dir = ALL_PROJECTS_DIR.$_SESSION['member_session']['team'].'/'.$target;
	
	if($name != ""){
	
		if(file_exists($dir)){
			$name = str_replace("/", "", $name);
			
			if(file_exists($dir.$name)){
				
				$i = 1;
				
				while(file_exists($dir.$name." ($i)")){
					$i++;
				}
				
				mkdir($dir.$name." ($i)", 0777);
			
			}else{
				mkdir($dir.$name, 0777);
			}
	
			

		}
		
		file_list($target);
	
	}
	
}


function preview($target){

	$dir_preview = "../preview/";
	
	$file = ALL_PROJECTS_DIR.$_SESSION['member_session']['team'].'/'.$target;
	
	$google_supported_files = array("doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf", "pages", "ai", "psd", "tiff", "dxf", "svg", "eps", "ps", "ttf", "xps");
	
	$supported_images = array("jpg", "jpeg", "png", "gif");
	
	$other_supported_files = array("txt", "c", "h", "cpp", "js", "html", "xhtml", "php", "css");
	
	delete_old_files($dir_preview, 10);
	
	//vérification des droits 
	$extension = pathinfo($file, PATHINFO_EXTENSION);
	
	if(in_array($extension, $google_supported_files)){
		
		$copy = $dir_preview.random(8).'.'.$extension;
		copy($file, $copy);
		
		echo "<iframe class='preview_google' src='http://docs.google.com/gview?url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true' style='width:600px; height:500px;' frameborder='0'></iframe>";
		
	}else if(in_array($extension, $supported_images)){
		
		$copy = $dir_preview.random(8).'.'.$extension;
		copy($file, $copy);
		
		echo "<img class='preview_img' alt='image' src='".$copy."'/>";
		
	}else if(in_array($extension, $other_supported_files)){
	
		$content = file_get_contents($file);
		if($extension == "txt"){

			echo nl2br(htmlentities($content));

		}else{
		
			include_once('geshi/geshi.php');
		
			$languages = array("c" => "c", 
							   "h" => "c", 
							   "cpp" => "cpp", 
							   "js" => "javascript", 
							   "html" => "html4strict", 
							   "xhtml" => "html4strict", 
							   "php" => "php", 
							   "css" => "css");

			$geshi = new GeSHi($content, $languages[$extension], "geshi/geshi/");
			$geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);

			echo $geshi->parse_code();
		}
	}

}

function random($nb) {
	$string = "";
	$chaine = "abcdefghijklmnpqrstuvwxy0123456789";
	
	srand((double)microtime()*1000000);
	
	for($i=0; $i<$nb; $i++) {
		$string .= $chaine[rand()%strlen($chaine)];
	}
	return $string;
}

function delete_old_files($dir, $duration){
	
	if ($handle = opendir($dir)) {
	
	    while (false !== ($file = readdir($handle))) {
	        
	        if ($file != "." && $file != "..") {
	        
	        	if( (time() - filemtime($dir.$file)) > $duration){
	        	
	        		unlink($dir.$file);
	        	}

	        }
	    }
	    
	    closedir($handle);
	}
}

function edit_file($target){

	$file = ALL_PROJECTS_DIR.$_SESSION['member_session']['team'].'/'.$target;

	$supported_files = array("txt", "c", "h", "cpp", "js", "html", "xhtml", "php", "css");
	
	$extension = pathinfo($file, PATHINFO_EXTENSION);
	
	if(in_array($extension, $supported_files)){
	
		$content = file_get_contents($file);
		
		echo "<textarea class='edit_content'>".htmlentities($content)."</textarea>";
		echo "<br/><input class='send_edit' type='button' value='Editer'/>";
	}

}

function send_edit($target, $content){

	$file = ALL_PROJECTS_DIR.$_SESSION['member_session']['team'].'/'.$target;

	file_put_contents($file, $content);

}

function hasPreview($file){
	
	$google_supported_files = array("doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf", "pages", "ai", "psd", "tiff", "dxf", "svg", "eps", "ps", "ttf", "xps");
	
	$supported_images = array("jpg", "jpeg", "png", "gif");
	
	$other_supported_files = array("txt", "c", "h", "cpp", "js", "html", "xhtml", "php", "css");
	
	$extension = pathinfo($file, PATHINFO_EXTENSION);
	
	if((in_array($extension, $google_supported_files)) || (in_array($extension, $supported_images)) || (in_array($extension, $other_supported_files))){
	
		//vérifier les droits
		return "<span class='preview_file'>Preview</span>";
	}else{
		return "";
	}
}

function isEditable($file){
	
	$supported_files = array("txt", "c", "h", "cpp", "js", "html", "xhtml", "php", "css");
	
	$extension = pathinfo($file, PATHINFO_EXTENSION);
	
	if((in_array($extension, $supported_files))){
	
		//vérifier les droits
		return "<span class='edit_file'>Edit</span>";
	}else{
		return "";
	}
}

function isRemovable($file){

	if(true){//vérifier les droits	
		return "<span class=\"remove_file\"> Supprimer</span>";
	}else{
		return "";
	}
}

function isDownloadable($file){

	if(true){//vérifier les droits	
		return "<a href='download.php?file=".$file."'>Télécharger</a>";
	}else{
		return "";
	}
}

